package com.example.demo;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "manageuserServlet", value = "/manageuserServlet")
public class manageuserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");

        if ("list".equals(action)) {
            listUsers(request, response);
        } else if ("delete".equals(action)) {
            deleteUser(request, response);
        }
    }

    private void listUsers(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            // 数据库连接信息
            String url = "jdbc:mysql://localhost:3306/user";
            String username = "root";
            String password = "12345";

            // 建立数据库连接
            conn = DriverManager.getConnection(url, username, password);
            stmt = conn.createStatement();

            // 查询用户信息，使用正确的表字段
            String sql = "SELECT userNo, userPwd, userName, birthday FROM user2";
            rs = stmt.executeQuery(sql);

            // 将结果存储在request中，供JSP页面使用
            request.setAttribute("users", rs);

            // 转发到用户列表页面
            request.getRequestDispatcher("/userList.jsp").forward(request, response);

        } catch (SQLException e) {
            e.printStackTrace();
            response.getWriter().write("查询用户信息时出现错误：" + e.getMessage());
        } finally {
            // 关闭资源
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    private void deleteUser(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 注意：根据数据库表，userNo 可能是字符串类型，这里若数据库中是数值类型可继续用 int，若不确定建议用 String
        String userId = request.getParameter("id");
        Connection conn = null;
        PreparedStatement stmt = null;

        try {
            String url = "jdbc:mysql://localhost:3306/user";
            String username = "root";
            String password = "12345";

            conn = DriverManager.getConnection(url, username, password);
            String sql = "DELETE FROM user2 WHERE userNo = ?";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, userId);

            stmt.executeUpdate();

            // 删除成功后重定向到用户列表
            response.sendRedirect(request.getContextPath() + "/manageuserServlet?action=list");

        } catch (SQLException e) {
            e.printStackTrace();
            response.getWriter().write("删除用户时出现错误：" + e.getMessage());
        } finally {
            try {
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");

        if ("add".equals(action)) {
            addUser(request, response);
        } else if ("update".equals(action)) {
            updateUser(request, response);
        }
    }

    private void addUser(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String userNo = request.getParameter("userNo");
        String userPwd = request.getParameter("userPwd");
        String userName = request.getParameter("userName");
        String birthday = request.getParameter("birthday");

        Connection conn = null;
        PreparedStatement stmt = null;

        try {
            String url = "jdbc:mysql://localhost:3306/user";
            String dbUsername = "root";
            String dbPassword = "12345";

            conn = DriverManager.getConnection(url, dbUsername, dbPassword);
            String sql = "INSERT INTO user2 (userNo, userPwd, userName, birthday) VALUES (?, ?, ?, ?)";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, userNo);
            stmt.setString(2, userPwd);
            stmt.setString(3, userName);
            stmt.setString(4, birthday);

            stmt.executeUpdate();

            response.sendRedirect(request.getContextPath() + "/manageuserServlet?action=list");

        } catch (SQLException e) {
            e.printStackTrace();
            response.getWriter().write("添加用户时出现错误：" + e.getMessage());
        } finally {
            try {
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    private void updateUser(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String userNo = request.getParameter("userNo");
        String userName = request.getParameter("userName");
        String userPwd = request.getParameter("userPwd");
        String birthday = request.getParameter("birthday");

        Connection conn = null;
        PreparedStatement stmt = null;

        try {
            String url = "jdbc:mysql://localhost:3306/user";
            String dbUsername = "root";
            String dbPassword = "12345";

            conn = DriverManager.getConnection(url, dbUsername, dbPassword);
            String sql = "UPDATE user2 SET userName = ?, userPwd = ?, birthday = ? WHERE userNo = ?";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, userName);
            stmt.setString(2, userPwd);
            stmt.setString(3, birthday);
            stmt.setString(4, userNo);

            stmt.executeUpdate();

            response.sendRedirect(request.getContextPath() + "/manageuserServlet?action=list");

        } catch (SQLException e) {
            e.printStackTrace();
            response.getWriter().write("更新用户时出现错误：" + e.getMessage());
        } finally {
            try {
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}